<template>
  <div class="m-2 mr-0 overflow-hidden bg-white">
    <BasicTree
title="字典组列表" treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" :clickRowToExpand="false"
      :treeData="treeData" :actionList="actionList" :treeHeaderAction="treeHeaderAction"
      :fieldNames="{ key: 'dictCode', title: 'dictName' }" @select="handleSelect" search 
      :filterFn="filterFn"></BasicTree>
    <DictContentModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, h, createVNode } from 'vue'
import { BasicTree, TreeItem } from '@/components/Tree'
import { getDictList, deleteDict, addorUpdateDict } from '@/api/sys/dict';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import DictContentModal from './DictContentModal.vue'
import { useModal } from '@/components/Modal'
import { Modal } from 'ant-design-vue';

defineOptions({ name: 'DictTree' })
defineExpose({
  handlePlus,
});
const emit = defineEmits(['select'])
const [registerModal, { openModal }] = useModal()
const treeData = ref<TreeItem[]>([])

async function fetch(dictCode='') {
  const res = await getDictList({
    dictCode: dictCode
  })
  const formateRes = res.map(item => ({
    ...item, dictNameCopy: item.dictName
  }))
  emit('select', formateRes[0].dictCode)
  treeData.value = (formateRes) as unknown as TreeItem[]
}

function handleSelect(keys) {
  emit('select', keys[0])
}

const actionList: TreeActionItem[] = [
  {
    render: (node) => {
      return h(EditOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          handleEdit(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(DeleteOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          showConfirm(node)

        },
      });
    },
  },
];

const showConfirm = (node) => {
  Modal.confirm({
    title: '确认删除该字典组?',
    icon: createVNode(DeleteOutlined),
    // content: 'When clicked the OK button, this dialog will be closed after 1 second',
    onOk() {
      handleDelete(node);
    },
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() { },
  });
};

function handlePlus() {
  openModal(true, {
    isUpdate: false,
  })
}
const filterFn = (searchValue, node) => {
  console.log(node, 'node')
  return node['dictCode']?.includes(searchValue)
}
const treeHeaderAction = () => {
  openModal(true, {
    isUpdate: false,
  });
};

function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
  })
}

async function handleDelete(node: any) {
  console.log(node);
  await deleteDict(node.dictId)
  fetch()
}

function handleSuccess() {
  fetch()
}

onMounted(() => {
  fetch()
})
</script>
